<template>
  <div>
    <van-address-edit
      :area-list="citydata"
      :show-delete="isDeleteAddress"
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      slot="default"
      :address-info="AddressInfo"
    >
      <van-form :show-error="false">
        <van-field v-model="gender" readonly label="性别" name="性别" placeholder="请输入性别" @focus="isGenderShow = true" is-link :rules="rules.gender" />
        <van-field v-model="addressTag" readonly label="地址类别" name="地址类别" placeholder="请输入地址类别" @focus="isAddressTagShow = true" is-link :rules="rules.addressTag" />
        <div style="margin: 16px">
          <van-button v-show="false" ref="submitBtn"> </van-button>
        </div>
      </van-form>
    </van-address-edit>

    <!-- 选择性别弹出框 -->
    <van-popup v-model="isGenderShow" position="bottom">
      <van-picker title="请选择性别" show-toolbar :columns="['男', '女']" @confirm="onGender" @cancel="isGenderShow = false" />
    </van-popup>
    <!-- 选择性别弹出框 -->

    <!-- 选择地址标签弹出框 -->
    <van-popup v-model="isAddressTagShow" position="bottom">
      <van-picker title="请选择地址类别" show-toolbar :columns="['家', '公司', '学校']" @confirm="onaddressTag" @cancel="isAddressTagShow = false" />
    </van-popup>
    <!-- 选择地址标签弹出框 -->
  </div>
</template>
<script>
import citydata from '@/utils/citydata'
import { addAddress, editAddress, deleteAddress } from '@/api/address'

export default {
  name: '',
  props: {
    isDeleteAddress: {
      type: Boolean,
      required: false
    }
  },
  components: {},
  data() {
    return {
      citydata, // 地区列表
      isGenderShow: false, // 性别弹出框  默认false
      isAddressTagShow: false, // 地址类别弹出框  默认false
      gender: '', // 性别的双向绑定
      addressTag: '', // 地址类别的双向绑定
      Tag: ['home', 'school', 'company'],
      TagIndex: 0, // 地址类别的数组的索引
      rules: {
        // 性别和地址类别的表单项验证
        gender: [
          {
            required: false,
            message: '性别不能为空'
          }
        ],
        addressTag: [
          {
            required: false,
            message: '地址类别不能为空'
          }
        ]
      },
      AddressInfo: {},
      addressMsg: {}
    }
  },
  methods: {
    async onSave(val) {
      console.log(val)
      // 这里的if操作是 为了后来加的solt插槽和vant组件的样式风格统一
      if (this.gender === '') {
        this.rules.gender[0].required = true
        this.$refs.submitBtn.click()
        return
      } else if (this.addressTag === '') {
        this.rules.addressTag[0].required = true
        this.$refs.submitBtn.click()
        return
      }
      try {
        if (this.isDeleteAddress) {
          // 1. 展示保存中 loading
          this.$toast.loading({
            message: '保存中...',
            forbidClick: true, // 禁用背景点击
            duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
          })

          await editAddress(this.addressMsg.receive_address_id, {
            receive_user_name: val.name,
            receive_user_gender: this.gender === '男' ? 'male' : 'female',
            receive_user_phone: val.tel,
            receive_user_address: val.province + '+' + val.city + '+' + val.county + '+' + val.addressDetail,
            receive_address_tag: this.Tag[this.TagIndex],
            is_default: val.isDefault === true ? 'yes' : 'no'
          })

          this.$toast.success('修改成功')
          this.$router.back()
          localStorage.clear('addressMsg') // 修改操作成功后 删除传递过来的本地存储数据
        } else {
          // 1. 展示保存中 loading
          this.$toast.loading({
            message: '保存中...',
            forbidClick: true, // 禁用背景点击
            duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
          })

          // 发送新增地址请求
          await addAddress({
            receive_user_name: val.name,
            receive_user_gender: this.gender === '男' ? 'male' : 'female',
            receive_user_phone: val.tel,
            receive_user_address: val.province + '+' + val.city + '+' + val.county + '+' + val.addressDetail,
            receive_address_tag: this.Tag[this.TagIndex],
            is_default: val.isDefault === true ? 'yes' : 'no'
          })
          this.$toast.success('保存成功')
          this.$router.back()
        }
      } catch (err) {
        this.$toast.fail('操作失败请稍后重试')
      }
    },
    async onDelete() {
      try {
        // 1. 展示删除中 loading
        this.$toast.loading({
          message: '删除中...',
          forbidClick: true, // 禁用背景点击
          duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
        })
        await deleteAddress(this.addressMsg.receive_address_id)
        console.log(this.addressMsg.receive_address_id)
        this.$toast.success('删除成功')
        this.$router.back()
        localStorage.clear('addressMsg') // 删除操作成功后 删除传递过来的本地存储数据
      } catch (err) {
        this.$toast.fail('操作失败请稍后重试')
      }
    },
    onGender(value, index) {
      this.gender = value
      this.isGenderShow = false
    },
    onaddressTag(value, index) {
      this.TagIndex = index
      this.addressTag = value
      this.isAddressTagShow = false
    }
  },

  created() {
    // 渲染用户收货信息
    if (this.isDeleteAddress) {
      this.addressMsg = JSON.parse(localStorage.getItem('addressMsg'))
      this.AddressInfo.name = this.addressMsg.receive_user_name
      this.AddressInfo.tel = this.addressMsg.receive_user_phone

      if (this.addressMsg.is_default === 'yes') {
        this.AddressInfo.isDefault = true
      } else {
        this.AddressInfo.isDefault = false
      }

      this.gender = this.addressMsg.receive_user_gender === 'male' ? '男' : '女'

      if (this.addressMsg.receive_address_tag === 'school') {
        this.addressTag = '学校'
      } else if (this.addressMsg.receive_address_tag === 'home') {
        this.addressTag = '家'
      } else {
        this.addressTag = '公司'
      }

      const newArr = this.addressMsg.address.split('+')

      for (const k in citydata.province_list) {
        if (citydata.province_list[k] === newArr[0]) {
          this.AddressInfo.areaCode = k
          break
        }
      }

      for (const k in citydata.city_list) {
        if (citydata.city_list[k] === newArr[1]) {
          this.AddressInfo.areaCode = k
          break
        }
      }

      for (const k in citydata.county_list) {
        if (citydata.county_list[k] === newArr[2]) {
          this.AddressInfo.areaCode = k
          break
        }
      }

      this.AddressInfo.addressDetail = newArr[3]
    }
  },
  computed: {},
  mounted() {},
  watch: {}
}
</script>
<style scoped lang="less"></style>
